import React, { Component } from 'react';
import { Badge, Button, message, Popconfirm, Radio } from 'antd';
import { messages } from 'share/common';
import moment from 'moment'
import SlideFrame from 'components/slide-frame';
import AdvancedTable from 'components/advanced-table';
import auditBasisService from 'containers/finance-setting/audit-basis-config/audit-basis-service';
import { connect } from 'react-redux';
import { permission } from 'containers/finance-setting/permisson';
import bookDateSetting from '../book-date-setting/detail'
import 'styles/finance-setting/audit-basis-config/book-date-setting.scss';

const { SimpleTable } = AdvancedTable;

@connect(mapStateToProps)
@permission
class AuditBasisConfig extends Component {

  auditRef = null;

  static propTypes = {};

  state = {
    loading: false,
  };

  searchForm = [{
    id: 'levelOrgIds',
    label: messages('expense-14.key307')/*所属组织*/,
    component: 'Chooser',
    props: {
      type: 'select_set_of_books',
      labelKey: 'setOfBooksName',
      valueKey: 'setOfBooksId',
    },
    dataIndex: 'levelOrgName',
    parser: value => ({
      levelOrgIds: value ? value.map(item => item.id) : null
    })
  }, {
    id: 'distLevelOrgIds',
    label: messages('expense-14.key310')/*启用公司*/,
    component: 'Chooser',
    props: {
      type: 'priority_company',
      labelKey: 'name',
      valueKey: 'id'
    },
    dataIndex: 'distLevelOrgName',
    parser: value => ({
      distLevelOrgIds: value ? value.map(item => item.id) : null
    })
  }, {
    id: 'startDate',
    label: messages('expense-14.key308')/*开始时间*/,
    component: 'DateRangePicker',
    dataIndex: 'startDate',
    parser: value => ({
      startDateStartParam: value && value[0] ? moment(value[0])
        .format('YYYY-MM-DD 00:00:00') : null,
      startDateEndParam: value && value[1] ? moment(value[1])
        .format('YYYY-MM-DD 23:59:59') : null
    })
  }, {
    id: 'endDate',
    label: messages('expense-14.key309')/*结束时间*/,
    component: 'DateRangePicker',
    dataIndex: 'endDate',
    parser: value => ({
      endDateStartParam: value && value[0] ? moment(value[0])
        .format('YYYY-MM-DD 00:00:00') : null,
      endDateEndParam: value && value[1] ? moment(value[1])
        .format('YYYY-MM-DD 23:59:59') : null
    })
  }, {
    id: 'bookDate',
    label: messages('expense-14.key292')/*记账日期*/,
    component: 'DateRangePicker',
    dataIndex: 'bookDate',
    parser: value => ({
      bookDateStartParam: value && value[0] ? moment(value[0])
        .format('YYYY-MM-DD 00:00:00') : null,
      bookDateEndParam: value && value[1] ? moment(value[1])
        .format('YYYY-MM-DD 23:59:59') : null
    })
  }, {
    id: 'enabled',
    label: messages('common.column.status')/*状态*/,
    component: 'RadioGroup',
    dataIndex: 'enabled',
    children: [true, false].map(value => <Radio value={value}>
      {value ? messages('common.status.enable')/*启用*/ : messages('expense-14.key311')/*禁用temp*/}
    </Radio>)
  }];

  columns = [{
    dataIndex: 'levelCode',
    title: messages('expense-14.key312')/*层级*/,
    render: () => messages('expense-14.key313')/*帐套*/
  }, {
    dataIndex: 'levelOrgName',
    title: messages('expense-14.key307')/*所属组织*/,
  }, {
    dataIndex: 'distLevelOrgName',
    title: messages('expense-14.key310')/*启用公司*/
  }, {
    dataIndex: 'startDate',
    title: messages('expense-14.key308')/*开始时间*/,
    render: value => moment(value).format('YYYY-MM-DD HH:mm')
  }, {
    dataIndex: 'endDate',
    title: messages('expense-14.key309')/*结束时间*/,
    render: value => moment(value).format('YYYY-MM-DD HH:mm')
  }, {
    dataIndex: 'bookDate',
    title: messages('expense-14.key292')/*记账日期*/,
    render: value => moment(value).format('YYYY-MM-DD')
  }, {
    dataIndex: 'enabled',
    title: messages('common.column.status')/*状态*/,
    render: value => (
      <Badge
        status={value ? 'success' : 'error'}
        text={value ? messages('common.status.enable')/*启用*/ : messages('expense-14.key311')/*禁用temp*/}
      />
    )
  }, {
    dataIndex: 'operate',
    title: messages('common.operation')/*操作*/,
    render: (value, record) => (
      <Popconfirm
        title={messages('expense-14.key314')/*确认删除吗？*/}
        onConfirm={() => this.handleDelete(record)}>
        <a
          disabled={this.props.currentMenu && this.props.currentMenu.operationType !== 'RW' || record.readOnly}
          onClick={e => e.stopPropagation()}
        >
          {messages('common.delete')/*删除*/}
        </a>
      </Popconfirm>
    )
  }];

  service = (page, size, searchParams) => {
    return auditBasisService.getBookDateList(page, size, { ...searchParams });
  };

  handleDelete = (record) => {
    this.setState({ loading: true });
    auditBasisService.deleteBookDate(record.bookDateConfigId)
      .then(() => {
        this.auditRef.getList();
        message.success(messages('common.delete.successful')/*删除成功*/);
      })
      .finally(() => {
        this.setState({ loading: false });
      })
  };

  afterCloseSlideFrame = (flag) => {
    flag && this.auditRef.getList();
  };

  handleNewConfig = record => {
    SlideFrame.open({
      title: record ? messages('common.edit')/*编辑*/ : messages('common.create')/*新建*/,
      content: bookDateSetting,
      afterClose: this.afterCloseSlideFrame,
      params: {
        record: record || {}
      }
    }, this);
  };

  render() {
    const { loading } = this.state;
    return (
      <div className="book-date-setting">
        <SimpleTable
          showUtils
          tableName='book-date-setting-table'
          show={['tag-list', 'table-utils']}
          onRef={ref => this.auditRef = ref}
          loading={loading}
          columns={this.columns}
          service={this.service}
          searchForm={this.searchForm}
          rowKey="bookDateConfigId"
          onRow={record => ({
            onClick: () => this.handleNewConfig(record)
          })}
        >
          <div className="book-date-setting-tips">
            <div className="book-date-setting-tips-title">{messages('expense-14.key315')/*功能说明*/}：</div>
            <div className="book-date-setting-tips-content">
              1.{messages('expense-14.key316')/*若记账日期人工添加修改过，有值，则以该值落记账日期*/} <br/>
              2.{messages('expense-14.key317')/*若记账日期没有人工修改过，为空，则按下述逻辑落记账日期*/} <br/>
              &nbsp;&nbsp;&nbsp;&nbsp;a.{messages('expense-14.key318')/*优先按此页规则落值，若单据变成审核通过状态时间在规则定义的时间区间内，则命中规则，按定义的日期落记账日期*/} <br/>
              &nbsp;&nbsp;&nbsp;&nbsp;b.{messages('expense-14.key319')/*若没有命中任何规则，则以单据变成审核通过状态日期落记账日期*/}
            </div>
          </div>
          <Button
            type="primary"
            disabled={this.isReadOnly()}
            onClick={() => this.handleNewConfig()}
          >
            {messages('common.create')/*新建*/}
          </Button>
        </SimpleTable>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
  };
}

export default AuditBasisConfig;
